import { Message } from 'view-ui-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router'
import { codeMessage } from './config'

// 请求拦截器
export const requestInterceptors = {
    onFulfilled: (config) => {
        const userStore = useUserStore()
        // 添加token
        if (userStore.token) {
            config.headers.Authorization = `Bearer ${userStore.token}`
        }
        return config
    },
    onRejected: (error) => {
        Message.error('请求错误')
        return Promise.reject(error)
    }
}

// 响应拦截器
export const responseInterceptors = {
    onFulfilled: (response) => {
        const { code, message, data } = response.data

        // 这里根据你的后端接口规范来定义
        if (code === 200) {
            return data
        } else {
            Message.error(message || '请求失败')
            return Promise.reject(new Error(message || '请求失败'))
        }
    },
    onRejected: (error) => {
        const { response } = error
        
        if (response && response.status) {
            const errorText = codeMessage[response.status] || response.statusText
            const { status, config: { url } } = response

            Message.error(`请求错误 ${status}: ${url}`)
            console.error(errorText)

            // 处理401未授权的情况
            if (status === 401) {
                const userStore = useUserStore()
                userStore.logout()
                router.push('/login')
            }
        } else if (!response) {
            Message.error('网络异常，请检查网络连接')
        }

        return Promise.reject(error)
    }
} 